package com.xxzx.publicprevention.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


import com.xxzx.publicprevention.pojo.TbUploadfile;
import com.xxzx.publicprevention.service.TbUploadfileService;
import com.xxzx.publicprevention.util.FilePathTools;
import org.apache.commons.io.FileUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * tb_uploadfile (TbUploadfile)表控制层
 *
 * @author makejava
 * @since 2020-11-18 09:54:06
 */
@RestController
@RequestMapping("upload")
public class TbUploadfileController {
    /**
     * 服务对象
     */
    @Resource
    private TbUploadfileService uploadfileService;

    @Resource
    private FilePathTools filePathTools;

    String absolutePath = "E:\\file";

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public TbUploadfile selectOne(Integer id) {
        return this.uploadfileService.queryById(id);
    }

    @GetMapping("deleteById")
    public void deleteById(Integer id) {
        this.uploadfileService.deleteById(id);
    }


    @RequestMapping(value = "/uploadFile")
    @ResponseBody
    public JSONObject uploadFile(MultipartHttpServletRequest multipartRequest) throws IOException {

        JSONObject json = new JSONObject();
        List<TbUploadfile> attaList = new ArrayList<>();
        try {

            // 获取上传的文件
/*            MultipartFile multiFile = multipartRequest.getFile("file");*/
            Iterator<String> itr = multipartRequest.getFileNames();
            MultipartFile mpf = null;
            TbUploadfile atta = null;
            String newName = "";


            while (itr.hasNext()) {
                String name = itr.next();
                mpf = multipartRequest.getFile(name);
                newName = filePathTools.getNewPath(
                        mpf.getOriginalFilename());

                // for windows
//                FileUtils.copyInputStreamToFile(mpf.getInputStream(), new File(
//                        uploadRoot, newName));

                // for mac
                FileUtils.copyInputStreamToFile(mpf.getInputStream(), new File(
                        absolutePath, newName));

                atta = new TbUploadfile();
                atta.setFileName(mpf.getOriginalFilename());
                atta.setFileType(mpf.getContentType());
                atta.setFilePath(newName);
                atta.setUploadTime(new Date());
                TbUploadfile insert = uploadfileService.insert(atta);
                atta.setId(insert.getId());
                attaList.add(atta);
            }

            String Str = JSON.toJSONString(attaList);
            JSONArray array = JSONArray.parseArray(Str);

            json.put("list", array);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return json;


    }

    @RequestMapping(value = "/downloadFile/{id}")
    @ResponseBody
    public void downloadFile(@PathVariable int id, HttpServletRequest request,
                             HttpServletResponse response) throws IOException {
        try {
            TbUploadfile file = selectOne(id);
            if (file == null) {
                return;
            }


            File filePath = new File(absolutePath + "\\" + file.getFilePath());

            FileInputStream in = new FileInputStream(filePath);

            String downloadName = new String(file.getFileName().getBytes("GB2312"), "ISO8859-1");
            response.setContentType(file.getFileType());
            if (!(file.getFileType().startsWith("image") || file.getFileType().endsWith("pdf"))) {
                response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", downloadName));
            }
            FileCopyUtils.copy(in, response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


}